package com.rest.api;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.rest.core.auth.Auth;
import com.rest.core.dto.PageDTO;
import com.rest.core.dto.ReturnDTO;
import com.rest.entity.Book;
import com.rest.service.BookService;
import com.rest.utils.Code;

@Component
@Path("/books")
@Produces({ MediaType.APPLICATION_JSON })
public class BookApi {

	@Autowired
	private BookService bookService;

	@SuppressWarnings("rawtypes")
	@Path("")
	@GET
	public ReturnDTO getList() {
		PageDTO pageDTO = bookService.getList();
		return new ReturnDTO<PageDTO>(Code.SUCCESS_CODE, Code.SUCCESS_QUERY,
				pageDTO);
	}

	@SuppressWarnings("rawtypes")
	@Path("/{id}")
	@GET
	public ReturnDTO getById(@PathParam("id") Integer id) {
		Book book = bookService.getById(id);
		return new ReturnDTO<Book>(Code.SUCCESS_CODE, Code.SUCCESS_QUERY, book);
	}

	@SuppressWarnings("rawtypes")
	@Auth
	@Path("")
	@POST
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	public ReturnDTO save(@FormParam("bookName") String bookName,
			@FormParam("author") String author) {
		Book book = bookService.save(bookName, author);
		return new ReturnDTO<Book>(Code.SUCCESS_CODE, Code.SUCCESS_MSG, book);
	}

	@SuppressWarnings("rawtypes")
	@Auth
	@Path("")
	@PUT
	@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
	public ReturnDTO newEntity(@FormParam("id") Integer id,
			@FormParam("bookName") String bookName,
			@FormParam("author") String author) {
		bookService.newEntity(id, bookName, author);
		return new ReturnDTO<>(Code.SUCCESS_CODE, Code.SUCCESS_MODIFY);
	}

	@SuppressWarnings("rawtypes")
	@Auth
	@Path("/{id}")
	@DELETE
	public ReturnDTO delEntity(@PathParam("id") Integer id) {
		bookService.delEntity(id);
		return new ReturnDTO<>(Code.SUCCESS_CODE, Code.SUCCESS_DEL);
	}

}
